<template>
  <view>
    <view class="date-list">
      <view class="day-item font-size-sm" :class="[clickIndex==index ? 'active': 'normal']"
        v-for="(item,index) in dayList" :key="index" @click="handleOnClick(index)">
        <view>
          <text :class="{'color-grey': clickIndex!=index}">{{item.week}}</text>
        </view>
        <view>
          <text class="font-bold">{{item.day}}</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
  export default {
    date() {
      return {
        clickIndex: 0,
      }
    },
    props: {
      modelValue: {
        default: () => new Date()
      }
    },
    computed: {
      dayList() {
        return this.getDays(this.modelValue)
      }
    },
    created() {
      // 根据传入日期默认选中
      this.clickIndex = this.modelValue.getDate() - 1
    },
    methods: {
      handleOnClick(index) {
        this.clickIndex = index
        console.log(this.clickIndex)
        // #ifdef VUE2
        // 解决vue2点击后不更新页面bug
        this.$forceUpdate()
        // #endif
        const selectDate = new Date(this.modelValue)
        selectDate.setDate(this.dayList[index].day)
        this.$emit('selectDate', selectDate)
        this.$emit('update:modelValue', selectDate)
      },
      getDays(inDate) {
        // 获取当月最后一天日期
        const date = new Date(inDate.getFullYear(), inDate.getMonth() + 1, 0);
        // 获取当月天数
        const dayCount = date.getDate();
        // 获取当月1号星期几
        const initWeek = new Date(inDate.getFullYear(), inDate.getMonth()).getDay()
        const dayArray = []
        const weekArray = ['日', '一', '二', '三', '四', '五', '六']
        let week = initWeek + 1 //避免星期第一条为0
        for (let i = 0; i < dayCount; i++) {
          week = week % 7
          if (week == 0) { //若是星期最后一天重置
            week = 7
          }
          dayArray.push({
            day: i + 1,
            week: weekArray[week - 1],
          })
          week++
        }
        return dayArray
      }
    },
  }
</script>

<style scoped lang="scss">
  .date-list {
    width: 100vw;
    padding: 10px 0;
    display: flex;
    gap: 10px;
    overflow-x: scroll;

    .day-item {
      padding: 2px 12px;
      border-radius: 10px;
      box-shadow: 0 0 6rpx 0 rgba(0, 0, 0, 0.16);
      text-align: center;
    }
  }

  .normal {
    background-color: white;
    color: $uni-text-color;
  }

  .active {
    background-color: $uni-color-primary;
    color: white !important;
  }

  .font-size-sm {
    font-size: $uni-font-size-sm;
  }

  .font-bold {
    font-weight: bold;
  }

  .color-grey {
    color: $uni-text-color-grey;
  }
</style>